package com.gooluke.mybatis.registar;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

import java.util.Arrays;
import java.util.Set;

public class MyInterfaceScanner extends ClassPathBeanDefinitionScanner {

    public MyInterfaceScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
        // 只扫描接口
        addIncludeFilter((metadataReader, metadataReaderFactory) -> 
            metadataReader.getClassMetadata().isInterface());
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
        
        if (beanDefinitions.isEmpty()) {
            logger.warn("No interfaces found in specified packages: " + Arrays.toString(basePackages));
        } else {
            processBeanDefinitions(beanDefinitions);
        }
        
        return beanDefinitions;
    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
            
            // 获取接口的全限定名
            String interfaceName = definition.getBeanClassName();
            definition.getConstructorArgumentValues().addGenericArgumentValue(interfaceName);
            
            // 设置BeanClass为工厂类
            definition.setBeanClass(MyInterfaceFactoryBean.class);
        }
    }

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
    }
}